rm(list = ls())

library(tidyverse)
library(lfe)
library(readxl)
library(broom)

## Helper functions

source('code/helper_functions.R')

## Data

df <- readRDS("data/mlfz_data.rds")

## Outcome list

o_list <- c(
    "TZ_u_faz_nw_bin", 
    "TZ_u_bild_nw_bin", 
    "TZ_u_sz_nw_bin", "TZ_u_welt_nw_bin",
    "index_nw_ratio_bin_national", "index_nw"
) %>% 
  paste0(. , '_mean_diff')

## Load Data

df <- df %>%
    dplyr::select(
        county_id_2018,
        year,
        one_of(o_list),
        matches("covar|treat")
    ) %>%
    mutate(treat_categorical4 = factor(treat_categorical4,
        levels = c(
            "NoChange",
            "DecAndInc",
            "Increase",
            "Decrease"
        )
    )) %>%
    filter(!year == 2013)

## Def covariates

covars <- c("covar_pop_total_diff", "covar_gdp_pc_diff")

##

res <- lapply(o_list, function(o) {
    ## Get DF

    df_temp <- df

    ## Message
    print(o)

    ## Prep

    df_temp$outcome <- df_temp %>% pull(!!o)
    df_temp <- df_temp %>%
        filter(!is.na(outcome) & !is.na(treat_categorical4)) %>%
        dplyr::select(
            outcome, year, county_id_2018,
            treat_categorical4, one_of(covars)
        )

    ## Estimate

    m1 <- felm(outcome ~ treat_categorical4 | year | 0 | county_id_2018,
        data = df_temp
    ) %>%
        tidy_felm() %>%
        mutate(fe = "year")
    

    ## Year + covars

    f <- paste0(
        "outcome ~ treat_categorical4 +",
        paste0(covars, collapse = "+"),
        "| year | 0 | county_id_2018"
    ) %>%
        as.formula()

    m2 <- felm(f, data = df_temp) %>%
        tidy_felm() %>%
        mutate(fe = "year_covars")

    rbind(m1, m2) %>%
        mutate(
            east = c("All"),
            outcome = !!o
        )
}) %>%
    reduce(rbind) %>%
    mutate(period = "now") %>%
    filter(!str_detect(term, "Intercept|covar"))


## Save results as rds

results <- res %>% 
  mutate(term = str_remove(term, 'treat_categorical4')) %>% 
  filter(!str_detect(term, 'Intercept|covar'))

## Save 

write_rds(results, 'data/Results_MediaConsumption.rds')


